<script setup lang="ts">
import { ref, markRaw } from "vue";
import { useColumns } from "./finance_order_columns";
import "plus-pro-components/es/components/search/style/css";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import "plus-pro-components/es/components/dialog-form/style/css";
import {
  addOrder,
  setProductOrder,
  getOrderInfo,
  getProductsByType
} from "@/api/finance";
import { getKeyVal } from "@/api/common";
import { districtString } from "@/utils/common";
import {
  PlusSearch,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import { type Action, ElMessageBox, ElMessage } from "element-plus";
import { getInfo } from "@/api/admin";
import { id } from "element-plus/es/locale";

const props = defineProps({
  userId: {
    type: Number,
    default: undefined
  },
  financeEdit: {
    type: Boolean,
    default: false
  },
  financeDelete: {
    type: Boolean,
    default: false
  }
});

const edit = ref(false);
const visible = ref(false);
const values = ref<FieldValues>({});

const addVisible = ref(false);
const addValues = ref<FieldValues>({});

const searchColumns: PlusColumn[] = [
  {
    label: "产品类型",
    width: 200,
    prop: "type",
    valueType: "select",
    options: async () => {
      try {
        const res = await getKeyVal("GoodsType");
        const list = [
          {
            label: "云盒",
            value: 1
          },
          {
            label: "水机",
            value: 3
          },
          {
            label: "充电宝",
            value: 4
          }
        ];
        list.push(
          ...res.data.map(item => {
            return { label: item.title, value: item.type };
          })
        );

        return list;
      } catch (error) {
        console.log(error, "error");
        return [];
      }
    }
  },
  {
    label: "订单状态",
    width: 200,
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "进行中",
        value: 1
      },
      {
        label: "已结束",
        value: 2
      },
      {
        label: "需要在签约",
        value: 4
      }
    ]
  },
  {
    label: "权重值",
    width: 200,
    prop: "weight",
    valueType: "input-number",
    tooltip: "请输入大于权重值的订单"
  }
];

const rules = {
  endTime: [
    {
      required: false,
      message: "上机时间必填"
    }
  ],
  district: [
    {
      required: false,
      message: "地区运营商必选"
    }
  ]
};

const addRules = {
  uId: [
    {
      required: true,
      message: "用户账号必填"
    }
  ],
  fgId: [
    {
      required: true,
      message: "商品必选"
    }
  ],
  num: [
    {
      required: true,
      message: "购买数量必填"
    },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("购买数量必须大于 0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  userName: [
    {
      required: true,
      message: "用户名必填"
    }
  ],
  address: [
    {
      required: true,
      message: "地址必填"
    }
  ]
};

const addFormColumns: PlusColumn[] = [
  {
    label: "下单用户",
    prop: "uId"
  },
  {
    label: "选择商品",
    prop: "fgId",
    valueType: "select",
    options: async () => {
      try {
        const res = await getProductsByType({
          type: params.value.type,
          status: 1
        });
        return res.data.map(item => ({
          label: `${item.title} | ${item.num}台起购 | 库存：${item.tai}`,
          value: item.fgId
        }));
        console.log(res, "res");
      } catch (error) {
        console.log(error, "error");
        return [];
      }
    }
  },
  {
    label: "用户名",
    prop: "userName",
    valueType: "input"
  },
  {
    label: "购买数量",
    prop: "num",
    valueType: "input-number"
  },
  {
    label: "是否需要支付",
    prop: "isPay",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  },
  {
    label: "是否分销",
    prop: "isDrp",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  }
];

const loadUserInfo = async () => {
  try {
    const res = await getInfo(addValues.value.account);
    addValues.value.uId = res.data.uId;
  } catch (error) {
    console.log(error, "error");
  }
};

const formColumns: PlusColumn[] = [
  {
    label: "上机时间",
    width: 120,
    prop: "endTime",
    valueType: "date-picker",
    fieldProps: {
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      type: "date",
      disabledDate: (date: Date) => {
        // 禁用今天及之前的日期
        return date.getTime() < new Date().setHours(24, 0, 0, 0);
      }
    },
    tooltip: "上机时间后一天"
  },
  {
    label: "地区-运营商",
    prop: "district",
    valueType: "select",
    options: [
      {
        label: "重庆-联通",
        value: "1"
      },
      {
        label: "广州-联通",
        value: "2"
      },
      {
        label: "成都-移动",
        value: "3"
      },
      {
        label: "山东-联通",
        value: "4"
      },
      {
        label: "河南-电信",
        value: "5"
      },
      {
        label: "云南-电信",
        value: "6"
      },
      {
        label: "上海-联通",
        value: "7"
      },
      {
        label: "浙江-移动",
        value: "8"
      }
    ]
  },
  {
    label: "台数",
    prop: "num",
    valueType: "input-number"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "radio",
    options: [
      {
        label: "收益中",
        value: "1"
      },
      {
        label: "已结束",
        value: "2"
      }
    ]
  },
  {
    label: "结算商品",
    prop: "settleFgId",
    valueType: "select",
    options: async () => {
      try {
        const res = await getProductsByType({
          type: params.value.type,
          status: -1
        });
        return res.data.map(item => ({
          label: item.title,
          value: item.fgId
        }));
        console.log(res, "res");
      } catch (error) {
        console.log(error, "error");
        return [];
      }
    }
  },
  {
    label: "释放值",
    prop: "release",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1 }
  },
  {
    label: "回报值",
    prop: "countincome",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1 }
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onKeywordChange,
  onSizeChange,
  params,
  loadData,
  onCurrentChange
} = useColumns(props.userId);

if (!props.financeDelete && !props.financeEdit) {
  columns.pop();
}

function deleteClick(row) {
  ElMessageBox.confirm("是否删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "error",
    icon: markRaw(Delete),
    callback: async (action: Action) => {
      // 在这里执行删除操作
      if (action === "confirm") {
        console.log("执行删除操作");
        try {
          const params2 = {
            type: params.value.type,
            orderId: row.orderId,
            isDelete: 1
          };
          const res = await setProductOrder(params2);
          loadData();
          ElMessage.success("删除成功");
        } catch (error) {
          console.log(error, "error");
        }
      }
    }
  });
}
const editClick = async row => {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getOrderInfo(row.orderId, params.value.type);
    Object.assign(values.value, res.data);
    values.value.endTime = res.data.sjTime;
    // values.value = { ...res.data };
    console.log(
      "%cres===>>>",
      "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
      "返回的",
      res,
      values.value
    );
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.log(error, "error");
  }
};
const add = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  // ElMessage.info("暂未开发该功能");
  // return;
  edit.value = false;
  values.value = {};
  addValues.value = {};
  addVisible.value = true;
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...value };
  confirmLoading.value = true;

  if (edit.value) {
    try {
      const params2 = {
        type: params.value.type,
        orderId: updatedValues.orderId,
        district: updatedValues.district,
        endTime: updatedValues.endTime,
        status: updatedValues.status,
        release: Number(updatedValues.release),
        countincome: Number(updatedValues.countincome),
        num: updatedValues.num,
        settleFgId: updatedValues.settleFgId
      };
      const filteredParams2 = Object.fromEntries(
        Object.entries(params2).filter(([_, value]) => value !== null)
      );
      await setProductOrder(filteredParams2);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addOrder(updatedValues);
      addVisible.value = false;
      confirmLoading.value = false;
      addFormRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "uId" || target.prop == "weight") {
    return;
  }
  onKeywordChange(value);
};
const formRef = ref();
const addFormRef = ref();
const defaultSearchState = ref({ type: 1 });
const searchState = ref({ type: 1 });
</script>

<template>
  <div class="flex flex-col">
    <ElPageHeader :icon="null">
      <template #title>
        <h3>订单管理</h3>
      </template>
      <!---
      <template #extra>
        <div class="flex flex-row items-end justify-end mb-4">
          <el-button type="primary" @click="add">
            <el-icon :size="15" color="#fff">
              <IconifyIconOffline :icon="Plus" />
            </el-icon>
            添加订单
          </el-button>
        </div>
      </template>
    -->
      <PlusSearch
        v-model="searchState"
        :defaultValues="defaultSearchState"
        class="mt-5"
        :columns="searchColumns"
        :hasUnfold="false"
        @reset="handleReset"
        @search="handleSearch"
        @change="handleChange"
      />
    </ElPageHeader>

    <pure-table
      ref="tableRef"
      showOverflowTooltip
      class="mt-2"
      border
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #status="{ row }">
        <el-tag
          v-if="
            row.status == '1' && row.endtime < Math.floor(Date.now() / 1000)
          "
          type="success"
          >收益中</el-tag
        >
        <el-tag v-else-if="row.status == '1'" type="primary">待上机</el-tag>
        <el-tag v-else-if="row.status == '2'" type="danger">已结束</el-tag>
        <el-tag v-else-if="row.status == '3'" type="primary">待付款</el-tag>
        <el-tag v-else-if="row.status == '4'" type="primary">需要再签约</el-tag>
        <el-tag v-else type="danger">未知状态</el-tag>
      </template>
      <template #district="{ row }">
        <span>{{ districtString(row.district) }}</span>
      </template>
      <template #contract="{ row }">
        <el-tag v-if="row.flowStatus === 1" type="success">已签约</el-tag>
        <el-tag v-if="row.flowStatus === 8" type="info">不需要签约</el-tag>
        <el-tag v-else type="danger">未签约</el-tag>
      </template>
      <template #operation="{ row }">
        <el-button
          v-if="props.financeEdit"
          type="primary"
          size="small"
          @click="editClick(row)"
          >编辑</el-button
        >
        <el-button
          v-if="props.financeDelete"
          type="danger"
          size="small"
          @click="deleteClick(row)"
        >
          删除
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      draggable
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="编辑订单"
      @confirm="handleSubmit"
    />
    <PlusDialogForm
      ref="addFormRef"
      v-model:visible="addVisible"
      v-model="addValues"
      draggable
      :form="{ columns: addFormColumns, rules: addRules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="添加订单"
      @confirm="handleSubmit"
    >
      <template #plus-field-uId>
        <div class="flex flex-row items-center gap-2">
          <el-input
            v-model="addValues.account"
            placeholder="请输入用户手机号"
            style="width: 100%"
          />
          <el-button type="primary" size="default" @click="loadUserInfo">
            确认用户
          </el-button>
          <div class="w-full">
            查询结果为<strong class="text-red-500">{{ addValues.uId }}</strong>
          </div>
        </div>
      </template>
    </PlusDialogForm>
  </div>
</template>

<style scoped>
::deep .wot-message-box__icon--warning {
  --el-messagebox-color: red;
  color: red !important;
  fill: red !important;
}
</style>
